package com.xiaoyu.lanling.feature.vip.viewholder

import `in`.srain.cube.views.list.ViewHolderBase
import android.graphics.drawable.GradientDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.utils.extensions.getViewTag
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.base.utils.extensions.setViewTag
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.event.vip.VipProductItemClickEvent
import com.xiaoyu.lanling.feature.vip.model.ProductItem

class ProductViewHolder : ViewHolderBase<ProductItem>() {

    private val onClickListener = View.OnClickListener {
        val item = it.getViewTag<ProductItem>() ?: return@OnClickListener

        VipProductItemClickEvent(item).post()
    }

    private var mBackground: ImageView? = null
    private var mTag: TextView? = null
    private var mDuration: TextView? = null
    private var mDesc: TextView? = null

    override fun createView(layoutInflater: LayoutInflater, parent: ViewGroup): View? {
        val view = layoutInflater.inflate(R.layout.vip_product_item, parent, false)
        mBackground = view.findViewById(R.id.background)
        mTag = view.findViewById(R.id.tag)
        mDuration = view.findViewById(R.id.duration)
        mDesc = view.findViewById(R.id.price_desc)

        mBackground?.setOnClickDebounceListener(onClickListener)

        return view
    }

    override fun showData(position: Int, itemData: ProductItem) {
        mBackground?.isSelected = itemData.highlight
        mTag?.visibility = if (itemData.vipTag.valid) View.VISIBLE else View.GONE
        mTag?.text = itemData.vipTag.desc
        (mTag?.background?.mutate() as? GradientDrawable)?.setColor(itemData.vipTag.color)
        mDuration?.text = itemData.duration
        mDesc?.text = AppContext.getString(R.string.vip_product_price_prefix, itemData.price)
        mBackground?.setViewTag(itemData)
    }
}